/**
 * @param {number[]} nums
 * @return {number}
 */
 var magicTower = function(nums) {
    const n = nums.length
    let sum = 1, i = 0, count = 0
    const stack = []
    while(i < n){
        if(nums[i] < 0)
            stack.push(nums[i])
        if(sum + nums[i] < 0){
            let min = Math.min(...stack)
            stack.splice(stack.indexOf(min), 1)
            let temp = nums.splice(nums.indexOf(min),1)
            nums.push(...temp)
            count++
            sum -= min
            sum += nums[--i]  
        }else
            sum += nums[i]
        i++
    }
    return sum >= 0 ? count : -1
};